package cn.icanci.ladybird.common.util.file;

import cn.icanci.ladybird.service.util.NginxService;
import cn.icanci.ladybird.service.util.impl.NginxServiceImpl;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Hashtable;

/**
 * @author: icanci
 * @date: Created in 2020/10/7 8:14
 * @classAction: 生成二维码上传到云服务器
 */
@SuppressWarnings("all")
@Component
public class MatrixToImageWriterUtils {
    private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;
    // 文件路径
    String rootPath = this.getClass().getResource("/").getPath();

    private MatrixToImageWriterUtils() {
    }

    /**
     * 获取 BufferedImage对象
     *
     * @param matrix BitMatrix对象
     * @return 返回BufferedImage对象
     */
    public static BufferedImage toBufferedImage(BitMatrix matrix) {
        // 获取宽度
        int width = matrix.getWidth();
        // 获取高度
        int height = matrix.getHeight();

        // 创建 RGB BufferedImage对象
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
            }
        }
        return image;
    }

    /**
     * 包数据写到文件中
     *
     * @param matrix BitMatrix 对象
     * @param format 二维码的图片格式
     * @param file   文件
     * @throws IOException
     */
    public static void writeToFile(BitMatrix matrix, String format, File file)
            throws IOException {
        BufferedImage image = toBufferedImage(matrix);
        if (!ImageIO.write(image, format, file)) {
            throw new IOException("Could not write an image of format "
                    + format + " to " + file);
        }
    }

    /**
     * 图片输出到流
     *
     * @param matrix BitMatrix 对象
     * @param format 二维码的图片格式
     * @param stream 输出流
     * @throws IOException
     */
    public static void writeToStream(BitMatrix matrix, String format, OutputStream stream) throws IOException {
        BufferedImage image = toBufferedImage(matrix);
        if (!ImageIO.write(image, format, stream)) {
            throw new IOException("Could not write an image of format " + format);
        }
    }

    /**
     * 写出png图片
     *
     * @param path            路径
     * @param couponBatchCode 二维码内容
     * @throws Exception
     */
    public static void writePng(String path, String couponBatchCode) throws Exception {
        // 二维码内容
        String text = couponBatchCode;
        // 二维码图片宽度
        int width = 300;
        // 二维码图片高度
        int height = 300;
        // 二维码的图片格式
        String format = "png";

        Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
        // 内容所使用字符集编码
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");

        BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);
        // 生成二维码 文件地址 是否存在不存在则新增
        File outputFile = new File(path);
        if (!outputFile.getParentFile().exists()) {
            outputFile.getParentFile().mkdirs();
        }
        if (!outputFile.exists()) {
            outputFile.createNewFile();
        }
        MatrixToImageWriterUtils.writeToFile(bitMatrix, format, outputFile);
    }

    /**
     * 根据输入的信息，生成二维码
     *
     * @param text 需要生成二维码的数据
     * @return 返回生成的云服务器地址
     */
    public static String createOrderInfoImg(String text, String title, Long orderId) throws Exception {
        String path = new MatrixToImageWriterUtils().rootPath + System.currentTimeMillis() + ".png";
        writePng(path, text);
        InputStream inputStream = new FileInputStream(new File(path));
        // 创建 上传对象
        NginxService nginxService = new NginxServiceImpl();
        Object aliyunPath = nginxService.uploadPicture(inputStream, title, orderId);
        inputStream.close();
        return aliyunPath.toString();
    }
}
